package com.hmall.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    public static final String AUTHORIZATION = "authorization";
    public static final String HEADER_NAME = "user-info";

    private  final AuthProperties authProperties;

    private final JwtTool jwtTool;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1，获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 2，判断请求是不是需要拦截
        if(isExcludePath(request.getURI().getPath())){
            return chain.filter(exchange);
        }
        // 3. 获取token
        List<String> tokenList = request.getHeaders().get(AUTHORIZATION);
        String token = null;
        if(CollectionUtil.isNotEmpty(tokenList)){
            token = tokenList.get(0);
        }

        // 4. 校验并且解析token
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            // 4.1 如果解析失败，返回401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 到此为止，结束请求
            return response.setComplete();
        }

        // 5. 传递用户信息
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header(HEADER_NAME, userId.toString()))
                .build();
        // 6. 放行
        return chain.filter(swe);
    }

    /**
     * 判断请求是否需要拦截
     * @param path 请求路径
     * @return 是否需要拦截
     */
    private boolean isExcludePath(String path) {
        return authProperties.getExcludePaths().stream().anyMatch(path::startsWith);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
